# node_a.py
import random
import grpc
from concurrent import futures
import time
import quotes_pb2
import quotes_pb2_grpc

A_QUOTES = [
    {
        "zh": "尽力而为，随遇而安。 — 西奥多·罗斯福",
        "en": "Do what you can, with what you have, where you are. — Theodore Roosevelt",
        "pic": "https://staticedu-wps.cache.iciba.com/image/b1e20fd1986c4caf666d78f8d0cb865a.jpg",
    },
    {
        "zh": "夏天里的美好，能治愈生命里的冬天。",
        "en": "The beauty of summer can heal the winter of your life.",
        "pic": "https://staticedu-wps.cache.iciba.com/image/0dfd35fcad9190747d8bd3cd2c91c758.jpg",
    },
]


# 是服务器时，需要实现服务器应实现的方法，在 proto 中定义
# 继承自 quotes_pb2_grpc 中的服务对象 QuoteServiceServicer
class QuoteServiceA(quotes_pb2_grpc.QuoteServiceServicer):
    def GetQuote(self, request, context):
        q = random.choice(A_QUOTES)
        return quotes_pb2.QuoteResponse(zh=q["zh"], en=q["en"], pic=q["pic"])


# 定义服务器，将实现的服务器的方法绑定在上面
def serve():
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=5))
    server.add_insecure_port("[::]:50051")
    quotes_pb2_grpc.add_QuoteServiceServicer_to_server(QuoteServiceA(), server)
    server.start()
    print("A 节点已启动，监听 50051")
    return server


# 当作客户端时，可以向 B 服务器发起请求
def call_b():
    with grpc.insecure_channel("localhost:50052") as channel:
        stub = quotes_pb2_grpc.QuoteServiceStub(channel)
        response = stub.GetQuote(quotes_pb2.Empty())
        print(f"A 节点作为客户端请求 B ，获得响应：\n{response.zh}")


if __name__ == "__main__":
    server = serve()
    try:
        time.sleep(1)  # 等待 B 启动
        call_b()
        server.wait_for_termination()
    except KeyboardInterrupt:
        server.stop(0)
